package com.cxyzy.demo

import android.os.Bundle
import android.view.View.GONE
import android.view.View.VISIBLE
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import com.afollestad.assent.Permission
import com.afollestad.assent.runWithPermissions
import com.amap.api.location.AMapLocationClient
import com.amap.api.location.AMapLocationClientOption
import com.amap.api.location.AMapLocationListener
import com.cxyzy.demo.Utils.isLocationProviderEnabled
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {
    private lateinit var mLocationClient: AMapLocationClient
    private var mLocationOption = AMapLocationClientOption()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        initMap()
        locateBtn.setOnClickListener { locate() }
    }

    private fun initMap() {
        mLocationClient = AMapLocationClient(applicationContext)
        mLocationOption.locationMode = AMapLocationClientOption.AMapLocationMode.Hight_Accuracy
        mLocationOption.isOnceLocation = true

        //获取最近3s内精度最高的一次定位结果：
        //设置setOnceLocationLatest(boolean b)接口为true，启动定位时SDK会返回最近3s内精度最高的一次定位结果。如果设置其为true，setOnceLocation(boolean b)接口也会被设置为true，反之不会，默认为false。
        mLocationOption.isOnceLocationLatest = true

        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.isNeedAddress = true
        //关闭缓存机制
        mLocationOption.isLocationCacheEnable = false

        //声明定位回调监听器
        val locationListener = AMapLocationListener { loc ->
            progressBar.visibility = GONE
            if (null != loc) {
                //解析定位结果
                val result = Utils.getLocationStr(loc)
                locationTv.text = result
            } else {
                locationTv.text = getString(R.string.locate_failed)
            }
        }
        //设置定位回调监听
        mLocationClient.setLocationListener(locationListener)
    }

    private fun locate() {
        runWithPermissions(Permission.ACCESS_FINE_LOCATION) {
            if (isLocationProviderEnabled(this@MainActivity)) {
                locationTv.text = ""
                progressBar.visibility = VISIBLE
                //给定位客户端对象设置定位参数
                mLocationClient.setLocationOption(mLocationOption);
                //启动定位
                mLocationClient.startLocation()
            } else {
                Utils.showAlert("本应用需要获取地理位置，请打开获取位置的开关", this)
            }
        }
    }

}
